﻿ai.loadRemotJsCss("/" + contextPath + "/dacp-res/catalog/common/js/dataplatIcon.js");
ai.loadRemotJsCss("/" + contextPath + "/dacp-res/catalog/dataindex/js/config.default.js");
var MainSheet=null;
var MainFram={
  buildTreeIndex:null,
  meta:null,
  metaModel:null,
  objtype:'TAB',
  init:function(){
	  this.objtype='TAB';
	  this.meta=new  AI.Meta({});
	  this.metaModel=this.meta.getMetaModel(objtype);
	   
	  this.metaInfo = this.metaModel.metaInfo;
	  this.querysql=config[objtype].sql ;
	  this.itemStore = new AI.JsonStore({
			                sql: this.querysql,
			                pageSize:20,
			                key:"XMLID"
	  });
	   
	  this.buildTopSearch();
	  this.buildTreeIndex();
	  this.buildAdvanceFilter();
	  this.buildList();
	 
	  this.buildSideButton();
	  this.buildShopCart();
  },
  initData:function(){////初始化界面所有数据
	  
  },
  buildTopSearch:function(){
	  ///搜索栏
	  $("#keyword").val(keyword);
	  $("#keywordsearch").click(function(){
			var keyword=$("#keyword").val();
			if(!keyword){alert("请输入关键字");return false;};
			var where="(objname like '%"+keyword+"%' or objname like '%"+keyword.toUpperCase()+"%')";
			 where+=" or (objcnname like '%"+keyword+"%' or objcnname like '%"+keyword.toUpperCase()+"%')";
			MainFram.listView.reload("select * from metaobj where "+where +" and objtype='TAB'");
		});
	  //一级横向导航栏
//	  $(".hd_cont_b_l a").click(function(){
//			 $(".hd_cont_b_l a").removeClass("active");
//			 $(this).addClass("active");
//			 var anckor=$(this).attr("href");
//			 window.location.href="/me/ftl/datastore/search?type"+anckor.replace("#","");
//			 //return false;
//	  });
	  
  },
  buildTreeIndex:function(){////左边的导航树
	  new AI.FlatTree({containerId:"showallIndexTree",dataurl:"cfg_datamgr"}); 
	  
	  $("#showallIndex").parent().hover(function() {
		    $("#showallIndex i").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
			$("#showallIndexTree").show();
		  },
	     function() {
			  $("#showallIndex i").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
			  $("#showallIndexTree").hide();
	 });
  },
  buildAdvanceFilter:function(){///高级过滤区
	  new AI.FilterArea({
		  containerId:"advance_filterarea",
		  hovertype:'show',
		  configItems:[
		      		 {type:'label',name:'层次',code:'DIM_DATALEVEL',storesql:"select ROWCODE,ROWNAME from metaedimdef where dimcode='DIM_DATALEVEL'",where:"DIM_PORTAL_PAHT1 in('{selfval}')"}
		      		,{type:'label',name:'周期',code:'DIM_DATACYCLE',storesql:"select ROWCODE,ROWNAME from metaedimdef where dimcode='DIM_DATACYCLE'",where:"DIM_PORTAL_PAHT1 in('{selfval}')"}
		      		,{type:'label',name:'状态',code:'DIM_DATASTATE',storesql:"select ROWCODE,ROWNAME from metaedimdef where dimcode='DIM_DATASTATE'",where:"DIM_PORTAL_PAHT1 in('{selfval}')"}
		      		,{type:'label',name:'重要程度',code:'DIM_ZB_ZBTYPE2',storesql:"select ROWCODE,ROWNAME from metaedimdef where dimcode='DIM_ZB_ZBTYPE2'",where:"DIM_PORTAL_PAHT1 in('{selfval}')"}
		      		,{type:'label',name:'重要程度',code:'DIM_PORTAL_PAHT1',storesql:"select ROWCODE,ROWNAME from metaedimdef where dimcode='DIM_PORTAL_PAHT1'",where:"DIM_PORTAL_PAHT1 in('{selfval}')"}
		      		,{type:'text',name:'字段名',code:'fieldname',where:"dataname like '%{selfval}%'" }
		      		,{type:'text',name:'表名',code:'dataname',where:"dataname like '%{selfval}%'"}
		    ],
		    onChange:function(where,vals){
		    	console.log(where);
		    }
	  });
  },
  buildList:function(){////对象列表区
	  var viewcarttpl='viewcarttpl';
	   
	  var listView = new AI.MetaList({
		    containerId: 'frame-right-main',
		    store: this.itemStore,
		    objtype: this.objtype,
		    title: config[objtype].title|| this.metaInfo.objname,
		    bodyHtml: '<div class="repeater-canvas col-md-12" style="padding-left:1px;padding-right:1px;height:100%;overflow:auto"></div> ',
		    columns: config[objtype].columns,
		    show: true,
		    card: {
		        tpl: config[objtype].tpl
		    },
		    preParaDataStore: function(store) {
		        for (var i = 0; i < MainFram.itemStore.getCount(); i++) {
		            var r = MainFram.itemStore.getAt(i);
		            r.set('ROWINDEX', i);
		            r.set('DBCNNAME', MainFram.transCode(baseStore, 'DBNAME', 'CNNAME', r.get('DBNAME')));
		            var cycle = MainFram.transCode(cycleStore, 'ROWCODE', 'ROWNAME', r.get('CYCLETYPE'));
		            r.set('CYCLECNTYPE', cycle);
		            r.set('TOPICCNNAME', MainFram.transCode(topicStore, 'RULECODE', 'RULENAME', r.get('TOPICNAME')));
		            if (r.get("FIELDNUM") == null) {
		                r.set('FIELDCNNUM', '--');
		            } else {
		                r.set('FIELDCNNUM', r.get("FIELDNUM"));
		            }
		            if (r.get("ROWNUM_VAL") == null) {
		                r.set('ROWNUM_CNVAL', '--');
		            } else {
		                r.set('ROWNUM_CNVAL', r.get("ROWNUM_VAL"));
		            }
		        }
		    },
		    dblClick: function(objid, objtype) {
		    	window.location="/me/ftl/datastore/apiDetail";
		       // ai.addTabSheet(objid, objid, "/me/ftl/me/portal/ai.meta.tabdetail?by=false&XMLID=" + objid);
		        return false;
		    },
		    click: function(e) {
		        var $this = $(e.currentTarget);
		        var objtype = $this.attr("OBJTYPE");
		        var $this = $(e.currentTarget);
		        var objtype=$this.attr("OBJTYPE");
		        if(objtype !='TAB'){
		        	return false;
		        };
		        $this.toggleClass('large');
		        
		        if($this.hasClass('large')){
		           if($('.detail',$this).length==0){
		            $('.fieldinfo',$this).append(MainFram.getColumnInfo($this.attr("id"))).addClass("detail");
		           };
		            
		           $(".detail",$this).show();
		           $(".detail a").click(function(e){
		               e.stopPropagation();
		               var $this = $(e.currentTarget);
		               $this.parents('.dacptiles').trigger('dblclick');
		           });
		       
		           $(".panel-heading",$this).addClass("header-panel");
		           $(".dacptiles.panel",$this).addClass("md-col");
		           $(".part-two",$this).addClass("color-chg");
		           $(".part-two",$this).addClass("class-chg");
		           $(".dacptiles .nav>li>a",$this).addClass("color-chg");
		           $(".nav>li>a>img",$this).addClass("icon-class");
		           $(".text-muted",$this).addClass("color-chg");
		           $(".nav i",$this).css("color","#EFF5FB");
		        }
		        else{
		          
		           $this.children().show();
		           $(".detail",$this).hide();
		           $(".panel-heading",$this).removeClass("header-panel");
		           $(".dacptiles.panel",$this).removeClass("md-col");
		           $(".part-two",$this).removeClass("color-chg");
		           $(".part-two",$this).removeClass("class-chg");
		           $(".dacptiles .nav>li>a",$this).removeClass("color-chg");
		           $(".nav>li>a>img",$this).removeClass("icon-class");
		           $(".text-muted",$this).removeClass("color-chg");
		           $(".nav i",$this).css("color","#5CAEA5");
		        };
		        //if(objtype=='TAB') 
		        $container.isotope('reLayout');
		        return false;
		        
		    },
		    contextMenu: function() {
		},
		onLoaded: function() {
			   
		        $(".repeater-list table td").attr("title", "");
		        $(".dacptiles .panel-heading").click(function() {
		            return false;
		        });
		        $(".dacptiles .panel-footer").click(function() {
		            return false;
		        });
		        
		        $("#advance_filter").click(function(){
		        	var filterAreaIsShow=  $("#advance_filterarea").parent().parent().is(":hidden");
		        	if(filterAreaIsShow) $("#advance_filterarea").parent().parent().show()
		        	else $("#advance_filterarea").parent().parent().hide();
		        });
		        MainFram.buildListCardAction();
		        MainFram.buildListHeadAction();
		        if(objtype=='TAB') MainFram.loadCardIsotope();
		        console.log("onLoaded");
		    },
		     "headerLeftHtml": '<ul class="nav navbar-nav navbar-left" style="height: 30px;"><li><a>全部</a></li><li></li><li><a>最新关注</a></li><li><a>最新推荐</a></li><li><a>最新申请</a></li> ' + '<li><form class="navbar-form  input-s-lg m-t m-l-n-xs hidden-xs" style="margin: 1px 0;"> <div class="form-group"> <div class="input-group input-group-sm"> <span class="input-group-btn">  <input type="text" class="form-control input-sm no-border keyword" placeholder="输入关键字..."><button type="button" class="btn btn-sm btn-icon btn-danger"><i class="fa fa-search"></i></button>  </span> </div> </div> </form></li>' + '<li><a href="#" id="advance_filter"><i class="fa fa-filter"></i>高级过滤</a></li>' + '<li><a href="#"><i class="fa fa-filter"></i>导出</a></li>'
		    //+'<li><button type="button" class="btn btn-default btn-sm dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">    排序方式 <span class="caret"></span>  </button></li>'
		    // +'<li><div class="btn-group"> <a type="" class="dropdown-toggle dropdown" data-toggle="dropdown"> Dropdown <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#">Dropdown link</a></li> <li><a href="#">Dropdown link</a></li> <li><a href="#">Dropdown link</a></li> </ul> </div></li>'
		     + '</ul>',
		   
		    toolbarconfig: config[objtype].toolbarconfig || [],
		    // fieldInfoArray:result.fieldInfoArray||[],
		    loadtype: 'dataindex'
		}); 
	  this.listView=listView;
  },
  buildListHeadAction(){
	        var objid = $(".dacptiles.panel.panel-success").attr("id");
	        var objInfo=this.meta.getMetaObjBaseInfo(objtype,objid,'record');
	        if(!objInfo){
	          console.log('Error,通过id:'+objid+'未获取到对象!');
	          return;
	        }
	        var dockplace="rightmenu";
	        var actionItems=this.meta.getMetaObjActionItems(objtype,dockplace);
	        //$("#card-choose a span").append('<div class="row"></div>');
	        var i=0;
	        $(".dacptiles ul").empty();
	        for(key in actionItems){
	          i++;
	          if(actionItems[key].getright){
	                actionItems[key].disabled = false;
	                var result = actionItems[key].getright(objInfo,_UserInfo,this.meta.getMetaInfo(objtype),'dataindex');
	                if(result == 'hide') {i--;continue;};
	                if(result == 'disabled'){
	                  actionItems[key].disabled = true;
	                }
	             }
	              var href = actionItems[key].url;
	              var icon = actionItems[key].icon;
	              var actName = actionItems[key].name;  
	             if(i>4){
	              break;
	             }
	             
	            $(".dacptiles ul").prepend('<li><a href="#" name="'+key+'" data-toggle="tooltip" data-placement="bottom" title="'+actName+'"><i class="'+icon+'"></i></a></li>');
	              // if(i%3==0){
	              //   $("#card-choose a span").append('<div class="row"></div>'); 
	              // }
	            
	          }
	          $(".dacptiles ul li a").click(function(e){
	        	
	            var $this = $(e.currentTarget);
	            var actionkey=$(this).attr('name');
	            if(actionkey=='addMyFav'){
	            	return false;
	            }
	            e.stopPropagation();
	            objid = $this.parent().parent().parent().parent().attr("id");
	            objInfo=MainFram.meta.getMetaObjBaseInfo(objtype,objid,'record');
	            MainFram.listView.metaAction({actionkey:$(this).attr('name')},objInfo);
	            
	          });
  },
  buildListCardAction:function(){
	  var objid = $(".dacptiles.panel.panel-success").attr("id");
      var objInfo=this.meta.getMetaObjBaseInfo(objtype,objid,'record');
      if(!objInfo){
        console.log('Error,通过id:'+objid+'未获取到对象!');
        return;
      }
      var dockplace="rightmenu";
      var actionItems=this.meta.getMetaObjActionItems(objtype,dockplace);
      //$("#card-choose a span").append('<div class="row"></div>');
      var i=0;
      $(".dacptiles ul").empty();
      for(key in actionItems){
        i++;
        if(actionItems[key].getright){
              actionItems[key].disabled = false;
              var result = actionItems[key].getright(objInfo,_UserInfo,this.meta.getMetaInfo(objtype),'dataindex');
              if(result == 'hide') {i--;continue;};
              if(result == 'disabled'){
                actionItems[key].disabled = true;
              }
           }
            var href = actionItems[key].url;
            var icon = actionItems[key].icon;
            var actName = actionItems[key].name;  
           if(i>4){
            break;
           }
           
          $(".dacptiles ul").prepend('<li><a href="#" name="'+key+'" data-toggle="tooltip" data-placement="bottom" title="'+actName+'"><i class="'+icon+'"></i></a></li>');
            // if(i%3==0){
            //   $("#card-choose a span").append('<div class="row"></div>'); 
            // }
          
        }
        $(".dacptiles ul li a").click(function(e){
          var $this = $(e.currentTarget);
          e.stopPropagation();
          objid = $this.parent().parent().parent().parent().attr("id");
          objInfo=meta.getMetaObjBaseInfo(objtype,objid,'record');
          listView.metaAction({actionkey:$(this).attr('name')},objInfo);
        }); 
  },
  loadCardIsotope : function(){
      $container = $('#myRepeater .repeater-thumbnail-cont');
      $container.isotope({
        itemSelector : '.thumbnail',
        masonry : {
          columnWidth : 80
        },
         itemPositionDataEnabled: true,
        masonryHorizontal : {
          rowHeight: 240
        },
        cellsByRow : {
          columnWidth : 240,
          rowHeight : 240
        },
        cellsByColumn : {
          columnWidth : 140,
          rowHeight : 120
        }
      });
    },
  buildSideButton:function(){
	  installBottomSideButton();
  },
  buildShopCart:function(){
	  buildShopCart();
  },
  getColumnInfo:function(xmlid){
	     var coldata = ai.getStoreData("select colname,colcnname from column_val where xmlid='"+xmlid+"' order by col_seq");
	     var html="";
	     for(var i=0;i<coldata.length;i++){
	      html+='<div class="col-xs-6"><small pull-left"> <i class="fa fa-clock-o"></i> '+coldata[i].COLNAME.toLowerCase()+","+coldata[i].COLCNNAME+'</small></div> ';
	      if(i>=18){
	        html+='<div class="col-xs-6"><a href="#" id="getMoreDetail"><span class="label label-primary pull-left">查看更多>></span></a></div>';
	        break;
	      }
	    };
	    return html; 
  },
  transCode:function(dimStore,keyfield,namefield,code){
	   if (dimStore.getCount() > 0) {
		   if (code != null) {
		            code = code.trim();
		            for (var i = 0; i < dimStore.getCount(); i++) {
		                if (dimStore.getAt(i).get(keyfield).trim() == code) {
		                    return store.getAt(i).get(namefield);
		                } else {
		                    continue;
		                }
		            }
		        } else {
		            code = '无'
		            return code;
		        }
		    } else {
		        return code == null ? '无': code;
		    }
	    return ! code ? '无': code;
  },
  treeNodeClick:function(id,title,url){
	 console.log(id,title,url);
	 if(!url) return false;
	 if(url.substr(0,1)!="/") url="/"+contextPath+"/"+url;
	 var urlParser = $.url(url);
	 var opener=urlParser.param("opener")||"content";///当前主窗口区替换
     var toUrl=url;
     if(!urlParser.attr('base')){
    	 var baseUrl = $.url().attr('base');
    	 if(url.substr(0,1)!="/") toUrl=baseUrl+"/"+url
    	 else toUrl=baseUrl+url
     };
     id=id.replaceAll("_","").replaceAll("-","");
	 
	  if(opener=="content") $("#frame-right-iframe").attr("src",toUrl)
	  else if (opener=="dialog") ai.openDialog("src",toUrl)
	  else if (opener=="tabsheet")  MainSheet.addTabSheet(id,title,toUrl,true,true );
  },
 
  dealUrl:function(url,param){
	  if(!param) param={};
	  param['contextPath']=contextPath;
	  param['TEAMCODE']=paramMap.TEAMCODE;
	   for(var key in param){  
		   url = url.replace('{'+key+'}',param[key]);
      }  
	  return url;
   }
    
};



 